import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import {ColorPicker} from "antd";
import {useTranslation} from "react-i18next";

interface SelectColorProps {
    onChange: Function,
    key: string,
    value: any,
    ds?: any
}


const SelectColor: FC<SelectColorProps> = (props) => {
    const {t} = useTranslation();

    const [value, setValue] = useState<any>(props.value);

    const presetsColor: any = useRef([{
        label: t("commonColors"),
        colors: [
            "rgba(255, 255, 255,.6)",
            "rgb(238, 238, 238)",
            "rgb(255, 255, 255)",
            "rgb(250, 84, 28)",
            "rgb(250, 140, 22)",
            "rgb(250, 173, 20)",
            "rgb(250, 219, 20)",
            "rgb(250, 0, 0)",
            "rgb(245, 34, 45)",
            "rgb(235, 47, 150)",
            "rgb(135, 206, 235)",
            "rgb(114, 46, 209)",
            "rgb(47, 84, 235)",
            "rgb(22, 119, 255)",
            "rgb(0, 0, 255)",
            "rgb(160, 217, 17)",
            "rgb(82, 196, 26)",
            "rgb(19, 194, 194)",
            "rgba(0, 0, 0,.6)",
            "rgb(0, 0, 0)"
        ]
    }]);

    useEffect(() => {
        const {ds = {}}: { ds: any } = props;
        setValue(ds.value || props.value);
    }, [props.ds]);

    const onChange = useCallback((color) => {
        props.onChange && props.onChange(color.toRgbString())
    }, [props.onChange]);

    const renderSelectColor = useMemo(() => {
        return (
            <ColorPicker size="small" showText value={value}
                         style={{width: "100%"}}
                         disabled={props.disabled}
                         presets={presetsColor.current}
                         placement={"bottomRight"}
                         onChange={onChange}/>
        )
    }, [value, props])

    return (renderSelectColor);
}
export default React.memo(SelectColor);